package com.xiu.weixin.service.wx;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.springframework.stereotype.Service;

import com.xiu.weixin.util.Consts;

//接入微信公众号
@Service
public class CheckTokenService {

	public boolean check(String signature, String timestamp, String nonce) {
		String[] strs = { Consts.TOKEN, timestamp, nonce };
		// 1）将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(strs);
		// 2）将三个参数字符串拼接成一个字符串进行sha1加密
		String src = strs[0] + strs[1] + strs[2];
		String mySignature = sha1(src);
		// 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		return mySignature.equals(signature);
	}

	public String sha1(String src) {
		// 获取一个加密对象
		try {
			MessageDigest md = MessageDigest.getInstance("sha1");
			byte[] digest = md.digest(src.getBytes());
			char chars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
			StringBuilder sb = new StringBuilder();
			for (byte b : digest) {
				sb.append(chars[(b >> 4) & 15]);
				sb.append(chars[b & 15]);
			}
			System.out.println("mySignature:" + sb);
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

}
